package com.zyg.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.utils.PageUtils;
import com.zyg.common.utils.Query;

import com.zyg.manager.dao.ContentDao;
import com.zyg.manager.entity.ContentEntity;
import com.zyg.manager.service.ContentService;


@Service("contentService")
public class ContentServiceImpl extends ServiceImpl<ContentDao, ContentEntity> implements ContentService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //获取查询条件
        Object key = params.get("key");
        //创建条件构造器
        QueryWrapper<ContentEntity> queryWrapper = new QueryWrapper<>();
        //进行条件赋值
        queryWrapper.like("title",key)
                    .or()
                    .eq("id",key)
                    .or()
                    .eq("category_id",key);
        IPage<ContentEntity> page = this.page(
                new Query<ContentEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }
    //从缓存中获取广告列表，第一次从数据库中获取，然后在存入缓存
    @Override
    public List<ContentEntity> findAll() {
        List<ContentEntity> contentList = null;
        //从缓存中获取广告列表
        String contentLists = redisTemplate.opsForValue().get("contentList");
        //判断是否缓存是否有值
        if(StrUtil.isNotBlank(contentLists)){
            contentList = JSON.parseArray(contentLists,ContentEntity.class);
        }else {
            //从数据库查询
            List<ContentEntity> list = this.list();
            //放入redis缓存中
            redisTemplate.opsForValue().set("contentList",JSON.toJSONString(list));
        }
        return contentList;
    }

}